package com.meilai.project.controller.web.finance.gear;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.meilai.project.dto.base.ApiResult;
import com.meilai.project.entity.finance.gear.Gear;
import com.meilai.project.exception.CommonException;
import com.meilai.project.service.gear.GearService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * <p>
 * 档位表 前端控制器
 * </p>
 *
 * @author xhy
 * @since 2022-12-08
 */
@RestController
@RequestMapping("/api/web/gear")
public class GearController {

    @Autowired
    private GearService gearService;

    private static final BigDecimal ten = new BigDecimal("10");

    private static final BigDecimal hundred = new BigDecimal("100");


    @GetMapping("/list")
    private ApiResult<List<Gear>> list() {
        List<Gear> list = gearService.list(Wrappers.<Gear>lambdaQuery().eq(Gear::getDeleted, false).orderByAsc(Gear::getGear));
        list.forEach(item -> {
            item.setTransaction_discount(item.getTransaction_discount().multiply(ten));
            item.setMaintenance_proportion(item.getMaintenance_proportion().multiply(hundred));
            item.setPersonal_proportion(item.getPersonal_proportion().multiply(hundred));
        });
        return ApiResult.ok(list);
    }


    @PostMapping("/save")
    private ApiResult<Boolean> save(@RequestBody Gear gear) {
        int count = gearService.count(Wrappers.<Gear>lambdaQuery().eq(Gear::getDeleted, false).eq(Gear::getGear, gear.getGear()));
        if (count > 0) {
            throw new CommonException("档位已经存在");
        }
        gear.setTransaction_discount(gear.getTransaction_discount().divide(ten, 2, RoundingMode.HALF_UP));
        gear.setMaintenance_proportion(gear.getMaintenance_proportion().divide(hundred, 2, RoundingMode.HALF_UP));
        gear.setPersonal_proportion(gear.getPersonal_proportion().divide(hundred, 2, RoundingMode.HALF_UP));
        return ApiResult.ok(gearService.save(gear));
    }

    @PostMapping("/edit")
    private ApiResult<Boolean> edit(@RequestBody Gear gear) {
        gear.setTransaction_discount(gear.getTransaction_discount().divide(ten, 2, RoundingMode.HALF_UP));
        gear.setMaintenance_proportion(gear.getMaintenance_proportion().divide(hundred, 2, RoundingMode.HALF_UP));
        gear.setPersonal_proportion(gear.getPersonal_proportion().divide(hundred, 2, RoundingMode.HALF_UP));
        return ApiResult.ok(gearService.updateById(gear));
    }

    @DeleteMapping("/remove")
    private ApiResult<Boolean> remove(@RequestParam("id") Long id) {
        return ApiResult.ok(gearService.update(Wrappers.<Gear>lambdaUpdate().set(Gear::getDeleted, true).eq(Gear::getId, id)));
    }
}
